package com.imooc.bilibili.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.imooc.bilibili.constant.UserMomentsConstant;
import com.imooc.bilibili.dao.UserMomentsDao;
import com.imooc.bilibili.entity.UserMoments;
import com.imooc.bilibili.enums.DeleteStateEnums;
import com.imooc.bilibili.enums.EnableStateEnums;
import com.imooc.bilibili.enums.MomentTypeEnums;
import com.imooc.bilibili.service.UserMomentService;
import com.imooc.bilibili.utils.RocketMqUtil;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.List;

@Service("userMomentService")
public class UserMomentServiceImpl implements UserMomentService {

    @Autowired
    private UserMomentsDao userMomentsDao;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public void insertUserMomentsService(UserMoments userMoments) throws Exception {
        //获取时间
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        userMoments.setMomentType(MomentTypeEnums.MOMENT_VIDEO.getCode());
        userMoments.setContentId(0L);
        userMoments.setEnableState(EnableStateEnums.START_USING.getCode());
        userMoments.setDeleteState(DeleteStateEnums.UN_DELETED.getCode());
        userMoments.setCreateTime(timestamp);
        userMoments.setUpdateTime(timestamp);

        userMomentsDao.insert(userMoments);
        //用户发布动态
        //通过ApplicationContext获取生产者对象
        DefaultMQProducer momentsProducer = (DefaultMQProducer) applicationContext.getBean("momentsProducer");
        //新建传递的消息对象
        Message message = new Message(UserMomentsConstant.TOPIC_MOMENTS, JSONObject.toJSONString(userMoments).getBytes(StandardCharsets.UTF_8));
        RocketMqUtil.syncSendMsg(momentsProducer,message);
    }

    @Override
    public List<UserMoments> queryUserSubscribeMomentsService(Long userId) {
        //从Redis中获取动态数据
        StringBuilder builder = new StringBuilder("subscibed-");
        String key = builder.append(userId).toString();
        String listStr = redisTemplate.opsForValue().get(key);
        return JSONArray.parseArray(listStr, UserMoments.class);
    }
}
